/**
 * 在有 storage使用的策略
 */
let pro = {
    workerManager:function (room){
        let spawnWorker = ()=>{
            let body = StationWork.getMiddleLevelWorkerBodyConfig(room);
            let partCnt = body.filter(e=>e==WORK).length;
            let boostLevel = StationLab.boostAbleLevel(room,"build",partCnt,1)
            let isBoost = room.creeps("carrier").length && boostLevel>=0;
            let task = []
            if(isBoost)task = StationLab.generatorBoostTask("build",partCnt,boostLevel)
            StationHive.trySpawn(room,room.name,body,"worker",task)
        }
        // log((room.storage.store[RESOURCE_ENERGY]-100000)/50000)
        let EnergyOver = (room.storage.store[RESOURCE_ENERGY]-120000)/50000>room.creeps("worker",false).length //能量溢出，可以多生爬来修
        let noWorker = room.creeps("worker",false).length<1;

        if(room.creeps("worker",false).length+room.creeps("carrier",false).length==0){// 或者爬都死光了
            spawnWorker();
        }else if(room.constructionSite.length) {//如果有工地也必生
            if(noWorker|| EnergyOver) // 如果一个都没有就生一个（保证有人去修工地,如果能量够可以多生几个
                spawnWorker();
        }else if(StationDefense.needBuildWall(room)){//如果需要修墙
            if(room.level<8 && (noWorker|| EnergyOver)){ // 8前 级优先修墙 如果一个都没有就生一个（保证有人去修工地,如果能量够可以多生几个
                spawnWorker();
            }else if(((room.storage.store[RESOURCE_ENERGY]>50000)&&noWorker)||EnergyOver){
                spawnWorker();
            }
        }else if((room.storage.store[RESOURCE_ENERGY]-300000)/50000>room.creeps("worker",false).length){ //如果能量还是太多了，就拼命修墙
            spawnWorker();
        }

        // }else if(room.level==8&&(needRepairWalls||room.constructionSite.length)){
        //
        //     if(room.creeps("worker",false).length<1||room.constructionSite.length&&(room.storage.store[RESOURCE_ENERGY]-100000)/50000>room.creeps("worker",false).length) //如果有工地且能量够的情况
        //         spawnWorker();
        // }
        // if((room.constructionSite.length||needRepairWalls||room.creeps("worker",false).length+room.creeps("carrier",false).length==0)  // 有工地的时候在造worker 或者全死光了
        //     &&(room.creeps("worker",false).length<1||(room.storage.store[RESOURCE_ENERGY]-100000)/50000>room.creeps("worker",false).length)){
        //     spawnWorker();
        // }

        if(room.storage.store[RESOURCE_ENERGY]<3000){
            _.values(room.memory[StationSources.stationName]).filter(e=>Game.getObjectById(e.id).energy).forEach(data=>{
                if(data["creeps"].filter(e=>Game.getObjectById(e)).length==0&&room.creeps().filter(e=>e.memory.role=="harvestEnergyKeeper").length==0){
                    let posLen = room[data["id"]].pos.nearPos(1).filter(e=>e.walkable()).length
                    let targetCnt = posLen*1.5 - room.creeps("worker").filter(e=>e.headTask()&&e.headTask().id == data["id"]).length;
                    if(Math.min(6,Math.ceil(targetCnt))>0){
                        let creep = room.creeps("worker").filter(e=>e.storeEmpty()&&e.isFree()).head()
                        if(creep)creep.addTask(StationSources.generatorReleaseAbleHarTask(data))
                    }
                }
            });
        }
    },
    unboostWorker:function(room,creep){
        if(creep.memory.needUnboost===undefined) creep.memory.needUnboost = creep.body.filter(e=>e.boost).length;
        if(creep.memory.needUnboost){
            let tasks = StationLab.generatorUnboostTask(room);
            if(tasks.length){
                creep.addTask(tasks);
                creep.memory.needUnboost = 0
            }
        }
    },
    workerManagerAfterCarrier:function (room){
        // worker 核心工作
        let isCarryFree = room.creeps("carrier").filter(e=>e.isFree()).length
        let StorageCarryEnergyTasks = StationCarry.generatorCarryStorageEnergyTask(room);
        let lowEnergyCarry = StationSources.generatorCarryEnergyTask(room,StationHive.HiveNeedToFill(room)?1200:500)
        room.creeps("worker").filter(e=>e.isFree()).forEach(creep=>{
            if(creep.storeEmpty()){
                if(creep.ticksToLive<80&&creep.memory.needUnboost===undefined){
                    pro.unboostWorker(room,creep)
                } else if(StorageCarryEnergyTasks.length>0){
                    creep.addTask(StorageCarryEnergyTasks)
                } else if(lowEnergyCarry.length){
                    creep.addTask(lowEnergyCarry.pop())
                }
            }else{
                if (!isCarryFree&&StationHive.HiveNeedToFill(room)) {
                    creep.addTask(StationHive.generatorFillHiveTask(room,creep));
                }else if(StationWork.constructionNeedBuild(creep.mainRoom())){
                    creep.addTask(StationWork.generatorBuildTask(creep))
                }else if(StationDefense.needBuildWallWorkerFree(room)){
                    creep.addTask(StationDefense.generatorRepairTask(room))
                }else if(room.level<8){
                    creep.addTask(StationUpgrade.generatorUpgradeTask(room));
                }
            }
        })
    },
    carrierOperatorBoost:function(room){
        //boost lab 操作
        let freeCarries = room.creeps("carrier").filter(e=>e.isFree()&&e.ticksToLive>50&&e.store.getUsedCapacity()==0);
        let task = StationLab.generatorOperatorBoostTask(room);
        if(task.length&&freeCarries.length)freeCarries.pop().addTask(task);
        if(!freeCarries.length)return;

        // 填充lab能量
        task = StationLab.generatorFillEnergyTask(room)
        if(task.length&&freeCarries.length)freeCarries.pop().addTask(task);
        if(!freeCarries.length)return;

        // lab 反应
        task = StationLab.generatorClearLabRes(room);
        if(task.length==0)task = StationLab.generatorFillReactionTask(room);
        if(freeCarries.length&&task.length) freeCarries.pop().addTask(task);
        if(!freeCarries.length)return;

    },
    carrierManager:function (room){
        pro.carrierOperatorBoost(room);

        let freeCarrie = room.creeps("carrier").filter(e=>e.isFree()&&e.storeEmpty()).head();
        let carryTasks = StationSources.generatorCarryEnergyFromLinkTask(room); // 优先整理中央link的资源，这个最快
        carryTasks.forEach(e=>{
            if(freeCarrie){freeCarrie.addTask(e);}
        })
        /**
         * 优先填tower 和 ext
         * 如果填完后还有能量就放回storage
         */
        let fillTowerTasks = StationTower.generatorFillEnergyTasks(room)
        let StorageCarryEnergyTasks = StationCarry.generatorCarryStorageEnergyTask(room);
        if(StorageCarryEnergyTasks.length){
            room.creeps("carrier").filter(e=>e.isFree()&&!e.storeContainsEnergyOtherResType()).forEach(creep=> {
                if (StationHive.HiveNeedToFill(room)) {
                    creep.addTask(StationHive.generatorFillHiveTask(room, creep));
                    if(creep.storeEmpty())creep.addTask(StorageCarryEnergyTasks);
                }else if(fillTowerTasks.length){
                    creep.addTask(fillTowerTasks.shift())
                    if(creep.storeEmpty())creep.addTask(StorageCarryEnergyTasks);
                }
            })
        }
        room.creeps("carrier").filter(e=>!e.storeEmpty()&&e.isFree()).forEach(e=>e.fillAll(room.storage))

        // container 能量
        let freeCarries = room.creeps("carrier").filter(e=>e.isFree()&&e.ticksToLive>50); // 从这里开始下面的任务最好大于150ttl
        carryTasks = StationSources.generatorCarryEnergyTask(room);
        carryTasks.forEach(e=>{
            if(freeCarries.length){freeCarries.pop().addTask(e);}
        })

        // 捡起任务 9tick更新一次，比较耗时 缓存起来
        let pickTasks = pro.pickTasksMap[room.name]||[]
        if ((Game.time+room.hashCode()) % 9 == 0) {
            pickTasks = StationCarry.generatorPickTask(room).concat(StationMineral.generatorCarryMineralTask(room))
        }
        if(freeCarries.length&&pickTasks.length){freeCarries.pop().addTask(pickTasks.shift());}
        pro.pickTasksMap[room.name] = pickTasks;


        if(StorageCarryEnergyTasks.length){
            if(!freeCarries.length)return;

            // 分配升级的运送
            let task = StationUpgrade.generatorFillEnergyTask(room.name,freeCarries.head().getPartCnt(CARRY)*50);
            if(freeCarries.length&&task.length)
                freeCarries.pop().addTask(task);
            if(!freeCarries.length)return;

            //填权力巢
            task = StationCarry.generatorFillPowerSpawnTask(room);
            if(freeCarries.length&&task.length)
                freeCarries.pop().addTask(task);
            if(!freeCarries.length)return;

            //填核弹人
            task = StationCarry.generatorFillNukerTask(room);
            if(freeCarries.length&&task.length)
                freeCarries.pop().addTask(task);
            if(!freeCarries.length)return;

            //填factory
            task = StationFactory.generatorFillTask(room);
            if(freeCarries.length&&task.length)
                freeCarries.pop().addTask(task);
            if(!freeCarries.length)return;



        }


    },
    pickTasksMap:{},
    trySpawnCarrier:function (room){ // 分配creep个数，最多7个，
        room.memory.carryBusy= room.memory.carryBusy||{}
        let carryBusyList = _.values(room.memory.carryBusy);
        let avgBusy = carryBusyList.reduce((a, b)=>a+b,0)/_.keys(carryBusyList).length
        // log(avgBusy,room.creeps("carrier",false).length,room.creeps("carrier",false).length*0.85)
        if((room.creeps("carrier",false).length<=0&&(room.storage[RESOURCE_ENERGY]>3000||room.creeps("harvestEnergyKeeper",false).length>0))||(
            room.creeps("carrier",false).length<=7&&
            avgBusy>room.creeps("carrier",false).filter(e=>!e.ticksToLive||e.ticksToLive>e.body.length*3).length*0.85)){
            StationHive.trySpawn(room,room.name,StationCarry.getCarrierBodyConfig(room),"carrier",[])
        }
        _.keys(room.memory.carryBusy).filter(e=>e<=Game.time-250).map(e=>delete room.memory.carryBusy[e])
        room.memory.carryBusy[Game.time] = room.creeps("carrier").filter(e => !e.isFree()).reduce((a) => a + 1, 0)
    },
    processPowerSpawn(room){
        if(room.powerSpawn){
            if (room.powerSpawn.store[RESOURCE_ENERGY] >= 50 && room.powerSpawn.store[RESOURCE_POWER] >= 1 ) {
                room.powerSpawn.processPower()
            }
        }
    },
    exec:function (room) {
        pro.processPowerSpawn(room)// 每tick都要处理
        if ((Game.time+room.hashCode()) % 3 != 0) return;
        ManagerAutoPlanner.tryAutoBuildHighLevel(room);



        StationCarry.transformLink(room);
        // worker 优先 carrier 的事件
        pro.workerManager(room); // 包括了生爬逻辑
        pro.carrierManager(room);
        // 等搬运工搬运剩下的才让worker帮忙
        pro.workerManagerAfterCarrier(room);



        pro.trySpawnCarrier(room); // 一定要在carrierManager后面
        StationSources.trySpawnHarKeeper(room);
        StationMineral.trySpawnHarKeeper(room);
        StationUpgrade.spawnUpgrader(room);


        //最后回收全部资源！
        // room.creeps("carrier").filter(e=>!e.storeEmpty()&&e.isFree()).forEach(e=>{
        //     e.fillAll(room.storage)
        // })


    }
}


global.StrategyHighLevel=pro;